package com.miyu.system.dao.data;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.blinkfox.fenix.specification.FenixSpecification;
import com.miyu.plugins.baseDao.BaseDao;
import com.miyu.system.pojo.system.SysDict;
import com.miyu.system.utils.page.PageLimit;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;


/**
 * 系统数据数据层
 * @author miyu
 */
@Repository
public interface SysDataDao extends BaseDao <SysDict,Integer > {


    /**
     * 查询系统字典
     * @param param 参数
     * @return {@link JSONArray}
     */
    default  Page<SysDict> querySysDict(JSONObject param) {
        String dictInfo = "dictInfo";
//        分页信息
        Pageable pageable = PageLimit.pageable(param, Sort.by("dictId").descending());

        return findAll(FenixSpecification.of(builder ->builder.andLike("dictCode",param.get(dictInfo),
                        StrUtil.isNotBlank(param.getString(dictInfo))).orLike("dictName",param.get(dictInfo),StrUtil.isNotBlank(param.getString(dictInfo))).build())
        ,pageable);
    }


    /**
     * -
     * 获取表名字
     * @return {@link JSONArray}
     */
    default JSONArray getTableName(String dataBase){

        StringBuffer sql = new StringBuffer();
        sql.append("select  table_name value,table_comment label  from information_schema.tables where table_schema='").append(dataBase).append("'");
        sql.append(" and table_comment <>'' ");
        sql.append(" order by table_name asc");
        return this.queryJSONArrayBySql(sql.toString());
    }

    /**
     * 获取表列通过表
     * @param param 参数
     * @return {@link JSONArray}
     */
    default JSONArray getTableColumnsByTable(JSONObject param,String dataBase){
        String tableName = param.getString("tableName");
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT column_name itemField,column_comment titleShow,ordinal_position orderNum,'' format ,data_type itemType, '1' isShow ");
        sql.append(" FROM INFORMATION_SCHEMA.COLUMNS where  table_schema='").append(dataBase).append("' and table_name='").append(tableName).append("'");
        sql.append(" order by ordinal_position");
        return this.queryJSONArrayBySql(sql.toString());
    }
}
